package subject1.lru;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2022/12/23--0:19
 * @Description 146. LRU 缓存
 */
class LRUCache {
    private class Node {
        int key;
        int value;
        Node next;
        Node prev;

        public Node(int key, int value, Node next, Node prev) {
            this.key = key;
            this.value = value;
            this.next = next;
            this.prev = prev;
        }

        public Node() {
        }
    }

    private Node dummyHead = new Node();
    private Node tail = dummyHead;

    private Map<Integer, Node> map = new HashMap<>();
    private int capacity;

    private int size;

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        Integer value = -1;
        Node node = map.get(key);
        if (node != null) {
            value = node.value;
            // 将Node节点移到双向链表的表头
            if (node.prev != dummyHead) {

                node.prev.next = node.next;
                if (node.next != null) {
                    node.next.prev = node.prev;
                } else {
                    // tail指向上一个元素
                    tail = tail.prev;
                }
                node.next = dummyHead.next;
                node.next.prev = node;
                dummyHead.next = node;
                node.prev = dummyHead;
            }
        }
        return value;
    }

    public void put(int key, int value) {
        if (size == capacity) {
            // 元素个数已达容量上限，将最近最少使用的元素移除
            tail.prev.next = null;
            Node q = tail;
            tail = tail.prev;
            q.prev = null;
            map.remove(q.key);
            size--;
        }
        Node node = new Node(key, value, dummyHead.next, dummyHead);
        if (dummyHead.next != null) {
            dummyHead.next.prev = node;
        }
        if (size == 1) {
            tail = node;
        }
        dummyHead.next = node;
        map.put(key, node);
        size++;
    }

    public static void main(String[] args) {
        LRUCache lRUCache = new LRUCache(2);
        lRUCache.put(1, 1);                         // 缓存是 {1=1}
        lRUCache.put(2, 2);                         // 缓存是 {1=1, 2=2}
        System.out.println(lRUCache.get(1));        // 返回 1
        lRUCache.put(3, 3);                         // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
        System.out.println(lRUCache.get(2));        // 返回 -1 (未找到)
        lRUCache.put(4, 4);                         // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
        System.out.println(lRUCache.get(1));        // 返回 -1 (未找到)
        System.out.println(lRUCache.get(3));        // 返回 3
        System.out.println(lRUCache.get(4));        // 返回 4
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
